// 1.502 检查jQuery库是否被正确加载
if (typeof jQuery === 'undefined') {
  console.error('jQuery library not found. Please make sure jQuery is loaded before this plugin.');
}

// 1.504 将变量存储在本地存储空间中，在页面加载时加载
var refreshInterval = localStorage.getItem('refreshInterval') || 60; // 默认为60秒
var autoRefresh = localStorage.getItem('autoRefresh') || '0'; // 默认为0，表示不自动刷新

// 1.502 插件代码在页面加载完成后继续执行
$(document).ready(function() {
  var wrapper = $('<div style="position: fixed; bottom: 80px; left: 0; width: 100%; background-color: white; padding: 10px;"></div>').appendTo('body');

  var button = $('<button>自动刷新</button>').appendTo(wrapper);
  var input = $('<input type="text" value="' + refreshInterval + '">').appendTo(wrapper);

  // 更新refreshInterval的值并保存到本地存储空间
  input.on('input', function() {
    refreshInterval = input.val();
    localStorage.setItem('refreshInterval', refreshInterval);
  });

  // 1.521 设置按钮的初始状态为自动刷新或停止刷新
  button.text(autoRefresh === '1' ? '停止刷新' : '自动刷新');
  
  var intervalId; // 用于存储刷新定时器的ID

  // 1.5211 刷新倒计时函数
  function startCountdown() {
    var countdown = refreshInterval;
    button.text('自动刷新 (' + countdown + '秒)');
    intervalId = setInterval(function() {
      countdown--;
      button.text('自动刷新 (' + countdown + '秒)');
      if (countdown === 0) {
        refreshPage();
        countdown = refreshInterval;
      }
    }, 1000);
  }

  // 1.521 切换按钮状态
  button.click(function() {
    if (autoRefresh === '0') {
      button.css('background-color', 'red');
      autoRefresh = '1';
      localStorage.setItem('autoRefresh', autoRefresh);
      startCountdown();
    } else {
      button.css('background-color', '');
      autoRefresh = '0';
      localStorage.setItem('autoRefresh', autoRefresh);
      clearInterval(intervalId);
      button.text('自动刷新');
    }
  });

  // 刷新页面函数
  function refreshPage() {
    location.reload();
  }

  // 检查并开始自动倒数
  if (autoRefresh === '1') {
    button.css('background-color', 'red');
    startCountdown();
  }
});
